home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Pointers!!??
- Date: 17 Mar 1996 09:04:50 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4ihgniINNck@keats.ugrad.cs.ubc.ca>
- References: <4ifhiu$b92@dfw-ixnews1.ix.netcom.com>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4ifhiu$b92@dfw-ixnews1.ix.netcom.com>,
- Andrew Heiz <ishky@ix.netcom.com> wrote:
- >Hi,
- >
- >I have a newbie question about pointers. Will sombody please explain
- >what the advantages of using pointers are. We learned about them in
- >class and programmed with them but we never learned why we were using
- >them. Why would it be more appropriate to use a pointer rather than a
- >variable name? Is it a space/time consideration?
-
- Nearly everything is a space/time consideration :) but in this case it's a
- more of a power/simplicity tradeoff.
-
- One advantage of pointers is that they can be dynamically manufactured at run
- time. You call malloc() to get a piece of memory and it gives you a new, unique
- pointer. Most non-trivial programs need to be written so that they don't impose
- compile-time constraints on the size of data sets---the maximum size of the
- data may not even be _known_ accurately beforehand; they need to be able to
- dynamically allocate new objects. Pointers are the method in C for keeping
- track of such objects.
-
- Another advantage is that pointers can be modified from referring to one object
- to refer to another. For example, if you know that a pointer refers to an array
- element, you can increment the pointer to refer to the next array element (if
- there is one). Or you can use a pointer to walk through a linked data
- structure, such as a tree, in which a parent node uses pointers to refer to
- children.
-
- Variable names are just compile-time labels, and are not themselves variable.
- They are bound to a single object in their scope, and so can't be used for
- these kinds of purposes.
-
- Finally, computers typically use physical pointers at the machine language
- level. On machines that use pointers (which is by far the majority of
- computers), the C pointer abstraction maps onto the machine's representation: a
- word which contains a memory address. Code that uses pointers is often more
- succint and efficient, though this is not a rule by any means.
-
- High-level language programs don't have to use pointers explicitly in order to
- benefit from them. Compilers will often use pointers to implement high-level
- features which don't involve abstracted pointers. For example, a loop which
- goes through an array of integers in Pascal, may still generate optimized
- machine code that uses pointers to access the memory.
- --
-
-